//
//  UserShareVC.m
//  easyTaxi
//
//  Created by ellenpage on 13-3-28.
//  Copyright (c) 2013年 ellenpage. All rights reserved.
//
#import "Constant.h"
#import "UserShareVC.h"
#import "PassValueClass.h"
#import <MessageUI/MessageUI.h>
#import "SocketObject.h"
#import "RequestCMD.h"

@interface UserShareVC ()<UITextFieldDelegate, UITextViewDelegate,UIAlertViewDelegate,MFMessageComposeViewControllerDelegate>

@property (retain, nonatomic) IBOutlet UITextField *sharePeopleTxtField;
@property (retain, nonatomic) IBOutlet UITextView *shareContentTxtView;
@property (retain, nonatomic) NSString *contentStr;
@property (retain, nonatomic) NSMutableArray *dataArray;
#define kFirsetTimeUse @"firstTimeUseAddressBook"

- (IBAction)goBack;
- (IBAction)resignKeyboard;
- (IBAction)goToPeopleView:(id)sender;
- (IBAction)goToMsmView;

@end

@implementation UserShareVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    _contentStr = nil;
    [super dealloc];
}

- (void)viewDidLoad
{
    [self loadData];
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)goBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)viewDidUnload
{
    [self setShareContentTxtView:nil];
    [self setSharePeopleTxtField:nil];
    [super viewDidUnload];
}


- (IBAction)resignKeyboard
{
    [_shareContentTxtView resignFirstResponder];
    [_sharePeopleTxtField resignFirstResponder];
}


- (void)loadData
{
    _dataArray = [[NSMutableArray alloc] init];

    _sharePeopleTxtField.delegate = self;
    _shareContentTxtView.delegate = self;
    
    NSString *tmpStr = [NSString stringWithFormat:@"Hi,我在使用易打车,欢迎你也使用,下载地址:http://t.cn/zTzJSJX"];
    _shareContentTxtView.text = tmpStr;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@""])
    {
        [_dataArray removeAllObjects];
    }
    
    if ([string isEqualToString:@"\n"])
    {
        [_sharePeopleTxtField resignFirstResponder];
        return NO;
    }
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"])
    {
        [_shareContentTxtView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (IBAction)goToPeopleView:(id)sender
{
    [YouMengEvent YouMengEvent:kOpenContractView];

    bool firstTimeUse = [[NSUserDefaults standardUserDefaults] objectForKey:kFirsetTimeUse];
    if (!firstTimeUse)
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kFirsetTimeUse];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"程序将调用手机的通讯录" message:@"点击确认以继续" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = kFirstTimeAlert;
        [alert show];
        [alert release];
        return;
    }
    
    ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
    picker.peoplePickerDelegate = self;
    [self presentModalViewController:picker animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = alertView.tag;
    switch (i) {
        case kFirstTimeAlert:
        {
            if (buttonIndex == 1)
            {
                ABPeoplePickerNavigationController *picker = [[ABPeoplePickerNavigationController alloc] init];
                picker.peoplePickerDelegate = self;
                [self presentModalViewController:picker animated:YES];
            }
        }
            break;
            
        default:
            break;
    }

}

#pragma mark - AddressBookView Delegate - 地址簿代理

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    NSString *personName  = (NSString*)ABRecordCopyValue(person,kABPersonFirstNameProperty);
    
    ABMultiValueRef phone = (ABMultiValueRef)((NSString*)ABRecordCopyValue(person,kABPersonPhoneProperty));
    for (int k = 0; k<ABMultiValueGetCount(phone); k++)
    {
        //获取該Label下的电话值
        NSString * personPhone = (NSString*)ABMultiValueCopyValueAtIndex(phone, k);
        NSLog(@"%@",personPhone);
        if ([_sharePeopleTxtField.text length] > 0)
        {
            if ([_sharePeopleTxtField.text length] == 11)
            {
                NSString *str = _sharePeopleTxtField.text;
                [_dataArray addObject:str];
            }
            
            if ([personPhone length] == 11)
            {
//                [_dataArray addObject:personPhone];
                NSString *str = [NSString stringWithFormat:@",%@<%@>",personName,personPhone];
                _sharePeopleTxtField.text = [_sharePeopleTxtField.text stringByAppendingString:str];
            }
        }
        else
        {
          
            if ([personPhone length] == 11)
            {
//                [_dataArray addObject:personPhone];
                NSString *str = [NSString stringWithFormat:@"%@<%@>",personName,personPhone];
                _sharePeopleTxtField.text = [_sharePeopleTxtField.text stringByAppendingString:str];
            }
        }
    }
    
//    NSLog(@"%@",_dataArray);
    [peoplePicker dismissModalViewControllerAnimated:YES];
   
    return YES;
}



- (IBAction)goToMsmView
{
    NSMutableArray *tmpArray = [[NSMutableArray alloc] init];

    _sharePeopleTxtField.text = [_sharePeopleTxtField.text stringByReplacingOccurrencesOfString:@"，" withString:@","];
    NSArray *array = [_sharePeopleTxtField.text componentsSeparatedByString:@","];
    
    if (array.count > 0)
    {
        tmpArray = [NSMutableArray arrayWithArray:array];
    }
    
    if (tmpArray.count > 0)
    {
        for (int i = 0; i < tmpArray.count ; i++)
        {
            NSString *str = [tmpArray objectAtIndex:i];
            NSRange urgentRange = [str rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"<"]];
            if (urgentRange.location != NSNotFound)
            {
                NSString *tmpStr = [str substringFromIndex:urgentRange.location];
                NSRange range = NSMakeRange (urgentRange.location + 1, [tmpStr length]-2);
                NSString *str2 = [str substringWithRange:range];
                NSLog(@"%@",str2);
                
                if ([self CheckInput:str2] == YES)
                {
                    if ([str2 length] == 11)
                    {
                        [_dataArray addObject:str2];
                    }
                }
            }
            else
            {
                if ([self CheckInput:str] == YES)
                {
                    if ([str length] == 11)
                    {
                        [_dataArray addObject:str];
                    }
                }
            }
        }
        
        if (_dataArray.count > 0)
        {
            [YouMengEvent YouMengEvent:kSendMMS];

            [self sendSMS:_shareContentTxtView.text recipientList:_dataArray];
        }
    }
}

-(BOOL)CheckInput:(NSString *)_text
{
    NSString *Regex = @"1\\d{10}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", Regex];
    return [emailTest evaluateWithObject:_text];
}

#pragma mark - SendMMS - 发送短信

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentModalViewController:controller animated:YES];
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    
    if (result == MessageComposeResultCancelled)
    {
        NSLog(@"Message cancelled");
    }
    else if (result == MessageComposeResultSent)
    {
        [PassValueClass sharedIntance].userUploadArray = _dataArray;
        NSLog(@"%@",_dataArray);
        NSLog(@"Message sent");
        [self requestNumList];
    }
    else
    {
        NSLog(@"Message failed");
    }
    
    [self dismissModalViewControllerAnimated:YES];
}


#pragma mark - Request NumList - 请求电话列表

- (void)requestNumList
{
    NSString *string    = [RequestCMD requestCMD:kUserUpLoadNum];
    NSMutableData *data = [RequestCMD getWantedData:string];
    [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kUserUpLoadNum];
}


@end
